<script setup>
import ImageUpload from "@/common/ImageUpload.vue";
import {onMounted, ref} from "vue";
import {ElMessage} from "element-plus";
import {addClassify, getClassifyById, updateClassify} from "@/api/classify.js";

//有id是编辑，没有id是添加
const {id} = defineProps({
  id: {
    type: Number,
    default: undefined
  },
})

onMounted(() => {
  if (id !== undefined) {
    getClassifyInfo(id)
  }
})

//获取分类信息
const getClassifyInfo = async (id) => {
  const {code, data, msg} = await getClassifyById(id);
  if (code !== 200) {
    ElMessage.error(msg)
    window.location.reload();
    return
  }
  form.value = data
}

//表单
const form = ref({
  id: undefined,
  url: undefined,
  name: undefined,
  status: 1,
})
//提交表单
const onSubmit = async () => {
  if (id === undefined) {
    await add()
  } else {
    await edit(id)
  }
}
const emit = defineEmits(['success'])
//添加分类
const add = async () => {
  const {code, msg} = await addClassify(form.value);
  if (code !== 200) {
    ElMessage.error(msg)
    return
  }
  ElMessage.success(msg)
  emit('success')
}
//修改分类
const edit = async () => {
  const {code, msg} = await updateClassify(form.value);
  if (code !== 200) {
    ElMessage.error(msg)
    return
  }
  ElMessage.success(msg)
  emit('success')
}
</script>


<template>
  <el-form label-width="100px">
    <el-form-item required label="分类名称">
      <el-input v-model="form.name"></el-input>
    </el-form-item>
    <el-form-item required label="分类背景图">
      <image-upload v-model:url="form.url"/>
    </el-form-item>
    <el-form-item required label="显示状态">
      <el-switch :active-value="1" :inactive-value="0" v-model="form.status"></el-switch>
    </el-form-item>
  </el-form>
  <div style="text-align: right; margin-top: 20px">
    <el-button type="primary" @click="onSubmit">提交</el-button>
  </div>

</template>

<style scoped lang="scss">

</style>
